package EP::EPC::Core::Data_Selection;

use strict;

use EP::Config;
use EP::Common;

use EP::EPC::Core;
use EP::EPC::Core::Data_Selection::exp;

use base 'EP::EPC::Core::Component';

sub process_component
    {
    my $self = shift;

    my ($meta, $new_dataset) = $self->process_selection($self->{src_dataset});

    my $process_result =
        { rows =>
            { type => "number"
            , label => "Rows selected"
            , value => $new_dataset->data->matrix->dim(1)
            }
        , columns =>
            { type => "number"
            , label => "Columns selected"
            , value => $new_dataset->data->matrix->dim(0)
            }
        , dataset_name => $new_dataset->{dataset}
        , src_dataset_id => $self->{src_dataset}->id
        , dst_dataset_id => $new_dataset->id
        };

    $process_result = { %$process_result, %$meta };

    $self->{CD}->{process_result} = $process_result;
    return $self->record_analysis_history ();
    }

sub process_selection
    {
    my $self = shift;

    $self->{session}->status("Processing selection ...");

    # at the moment only works with one dataset, but we could process
    # multiple ones with a foreach loop

    my ($meta, $sel_dataset);

    $_ = $self->{src_dataset}->type;

    SWITCH:
        {
        /exp/ && do
            {
            ($meta, $sel_dataset) = EP::EPC::Core::Data_Selection::exp::process_selection( $self, $self->{src_dataset}, $self->{query} );
            last SWITCH;
            };
        /seq/ && do
            {
            last SWITCH;
            };
        /ppi/ && do
            {
            last SWITCH;
            };
        /affy/ && do
            {
            throw EP::Common::Error ( -value => AFFY_TRANSFORM_RAW_DATA );
            last SWITCH;
            };
        }

    die "Failed to process selection" if not $sel_dataset;

    return ($meta, $sel_dataset);
    }

######################################################################
# Define query (grep) over column or row headers
######################################################################

sub define_regexp
    {
    my ($submitted_regexp) = @_; 

    my @r = split /\r\n|\r|\n/, $submitted_regexp;
    my @regexps;

    # do we need to manipulate regexps like this???
    foreach my $reg_exp ( @r )
        {
#       $reg_exp = "*" unless $reg_exp =~ /\S/;

#       $reg_exp =~ s/^\s+|\s+$//g;
#       $reg_exp =~ s/\*/\.\*/g;
        push @regexps, $reg_exp;
        }

    my $new_reg_exp = join ( "|", @regexps );

    print STDERR "[EP_Core] Defined regular expression: $new_reg_exp\n" if DEBUG;

    return $new_reg_exp;
    }

1;
